import { thousandSeparator } from '@/utils/variables.js';
/**
 * @description 每次执行生成随机id做为唯一标识符
 * @return {String} 随机数id
 * */
export const setUid = () => {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    var r = (Math.random() * 16) | 0,
      v = c == 'x' ? r : (r & 0x3) | 0x8;
    return v.toString(16);
  });
};

/**
 * @description 给对象结构的树形数据逐级设置id
 * @param {Object} tree 需要被设置id的对象
 * @param {String} idName  被设置的id名称
 * */
export const setTreeIds = (tree, idName = 'frontId') => {
  const uuid = () => {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
      const r = (Math.random() * 16) | 0,
        v = c == 'x' ? r : (r & 0x3) | 0x8;
      return v.toString(16);
    });
  };

  const traverse = node => {
    node[idName] = uuid();
    if (node.children) {
      node.children.forEach(child => traverse(child));
    }
  };

  traverse(tree);
};

// 树形结构中删除空children
/**
 * @description 数组树形结构中删除空children
 * @param {String} node 下拉框选项
 * @returns {Array} sda 66666
 * */
export const removeEmptyChildren = node => {
  if (!node || !node?.length) return [];
  node.forEach(item => {
    if ('children' in item && !item.children) {
      delete item.children;
    }
    if (item.children && item.children.length === 0) {
      delete item.children;
    } else if (item.children && item.children.length > 0) {
      removeEmptyChildren(item.children);
    }
  });
  return node;
};

// 若有重复nodeKey，则返回true
/**
 * @description 若数组中有重复nodeKey，则返回true
 * @param {arr} arr 下拉框选项
 * @param {String} nodeKey 下拉框选项
 * @returns {Boolean} sda 66666
 * */
export const checkArrLegal = (arr, nodeKey) => {
  let set = new Set();
  for (let item of arr) {
    let value = item[nodeKey];
    if (set.has(value)) {
      return true;
    }
    set.add(value);
  }
  return false;
};

// 输入框限制仅数字
export function inputDigit(num) {
  var n = String(num);
  var t = n.charAt(0);
  // 先把非数字的都替换掉，除了数字和.
  n = n.replace(/[^\d\.]/g, '');
  // 必须保证第一个为数字而不是.
  n = n.replace(/^\./g, '');
  // 保证只有出现一个.而没有多个.
  n = n.replace(/\.{2,}/g, '.');
  // 保证.只出现一次，而不能出现两次以上
  n = n.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.');
  // 限制两位小数
  n = n.replace(/^(\\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');
  // 如果第一位是负号，则允许添加
  if (t === '-') {
    n = '-' + n;
  }
  return n;
}

// 数组扁平化
export function flatten(arr, children = 'children') {
  return arr.reduce((result, item) => {
    return result.concat(item, Array.isArray(item[children]) ? flatten(item[children]) : []);
  }, []);
}

// table 统计
export function handleSummaryMethod({
  e,
  noPostfix = false,
  unit = {},
  totalName,
  countNumMap = null,
}) {
  const { columns, data } = e;
  let sums = [];
  if (!countNumMap) return [];
  if (data.length > 0) {
    columns.forEach((column, index) => {
      if (column.type === 'index') {
        sums[index] = totalName || 'Total';
        return;
      }
      Object.keys(countNumMap).forEach(prop => {
        if (column.property == prop) {
          const total = countNumMap[prop];

          let biPost = noPostfix?.length ? noPostfix.indexOf(prop) > -1 : noPostfix;
          sums[index] = total ? thousandSeparator(parseFloat(total).toFixed(2), biPost) : total;
          // 添加单位：例如%
          if (unit[prop] && sums[index]) sums[index] += unit[prop];
        }
      });
    });
    if (!sums.includes('Total')) {
      sums[0] = totalName || 'Total';
    }
  }
  return sums;
}
